<template>
  <view class="container">
    <button @click="downloadImage" class="download-btn">下载并显示图片</button>
    <view class="progress" v-if="progress > 0 && progress < 100">
      下载进度：{{ progress }}%
      <view class="progress-bar">
        <view class="progress-fill" :style="{ width: progress + '%' }"></view>
      </view>
    </view>
    <image :src="imagePath" mode="widthFix" class="show-image" v-if="imagePath"></image>
  </view>
</template>

<script>
export default {
  data() {
    return {
      progress: 0,
      imagePath: ''
    }
  },
  methods: {
    downloadImage() {
      this.progress = 0;
      this.imagePath = '';
      const imageUrl = 'https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg';
      const downloadTask = uni.downloadFile({
        url: imageUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            this.imagePath = res.tempFilePath;
            uni.showToast({
              title: '下载成功',
              icon: 'success'
            });
            // 下载成功后预览图片
            uni.previewImage({
              urls: [res.tempFilePath]
            });
          } else {
            uni.showToast({
              title: '下载失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('下载失败：', err);
          uni.showToast({
            title: '网络异常，下载失败',
            icon: 'none'
          });
        }
      });

      downloadTask.onProgressUpdate((res) => {
        this.progress = res.progress;
        // 打印下载进度日志
        console.log('下载进度:', res.progress + '%');
        console.log('已下载字节数:', res.totalBytesWritten);
        console.log('预计总字节数:', res.totalBytesExpectedToWrite);
      });
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.download-btn {
  width: 100%;
  padding: 20rpx 0;
  background-color: #007aff;
  color: white;
  border-radius: 8rpx;
  font-size: 34rpx;
  margin-bottom: 30rpx;
}

.progress {
  width: 100%;
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.progress-bar {
  width: 100%;
  height: 12rpx;
  background-color: #eee;
  border-radius: 6rpx;
  margin-top: 10rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #007aff;
  transition: width 0.3s ease;
}

.show-image {
  width: 100%;
  margin-top: 20rpx;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}
</style>